#include "SeqList.h"

// 对数据的管理:增删查改

// 初始化顺序表
void SeqListInit(SeqList *ps)
{
  ps->a = NULL;
  ps->size = 0;
  ps->capacity = 0;
}
void SeqListDestroy(SeqList *ps)
{
  assert(ps);
  if (ps->a != NULL)
  {
    free(ps->a);
    SeqListInit(ps);
  }
}

void SeqListPrint(SeqList *ps)
{
  for (int i = 0; i < ps->size; ++i)
  {
    printf("->%d", ps->a[i]);
  }
  printf("\n");
}

// 判断ps的大小是否足够，不够扩容
void SeqListCheckCapacity(SeqList *ps)
{
  assert(ps);
  if (ps->size == ps->capacity)
  {
    int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 4;
    SLDateType *tmp = (SLDateType *)realloc(ps->a, sizeof(SLDateType) * newCapacity);
    if (tmp == NULL)
    {
      perror("realloc failed...");
      return;
    }
    ps->a = tmp;
    ps->capacity = newCapacity;
  }
}

// 插入节点
void SeqListPushBack(SeqList *ps, SLDateType x)
{
  assert(ps);
  // 判断ps的大小是否足够，不够扩容
  SeqListCheckCapacity(ps);

  ps->a[ps->size++] = x;
}
void SeqListPushFront(SeqList *ps, SLDateType x)
{
  assert(ps);
  SeqListCheckCapacity(ps);
  // 所有元素往后边移动1个
  for (int i = ps->size; i > 0; --i)
  {
    ps->a[i] = ps->a[i - 1];
  }
  ps->a[0] = x;
  ps->size++;
}
void SeqListPopFront(SeqList *ps)
{
  assert(ps);
  assert(ps->size > 0);
  for (int i = 0; i < ps->size - 1; ++i)
  {
    ps->a[i] = ps->a[i + 1];
  }
  ps->size--;
}
void SeqListPopBack(SeqList *ps)
{
  assert(ps);
  assert(ps->size > 0);
  ps->size--;
}

// 顺序表查找
int SeqListFind(SeqList *ps, SLDateType x)
{
  assert(ps);
  for (int i = 0; i < ps->size; ++i)
  {
    if (ps->a[i] == x)
    {
      return i;
    }
  }
  return -1;
}
// 顺序表在pos位置插入x
void SeqListInsert(SeqList *ps, int pos, SLDateType x)
{
  assert(ps);
  assert(pos >= 0 && pos <= ps->size);
  SeqListCheckCapacity(ps);

  if (pos == 0)
  {
    SeqListPushFront(ps, x);
    return;
  }
  if (pos == ps->size)
  {
    SeqListPushBack(ps, x);
    return;
  }

  for (int i = ps->size; i > pos; --i)
  {
    ps->a[i] = ps->a[i - 1];
  }
  ps->a[pos] = x;
  ps->size++;
}
// 顺序表删除pos位置的值
void SeqListErase(SeqList *ps, int pos)
{
  assert(ps);
  assert(pos >= 0 && pos < ps->size);
  int begin = pos + 1;
  while (begin < ps->size)
  {
    ps->a[begin - 1] = ps->a[begin];
    ++begin;
  }
  ps->size--;
}